package com.autoscript.ext.sqlparse.service;

import com.alibaba.druid.sql.ast.SQLDataType;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLName;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.*;
import com.alibaba.druid.sql.parser.SQLParserUtils;
import com.alibaba.druid.sql.parser.SQLStatementParser;
import com.autoscript.ext.sqlparse.SqlParseConstant;
import com.autoscript.ext.sqlparse.entity.Column;
import com.autoscript.ext.sqlparse.entity.ForeignItem;
import com.autoscript.ext.sqlparse.entity.TableItem;
import com.autoscript.ext.xmldata.sql.parse.ISqlParse;
import com.autoscript.ui.helper.StringHelper;


import java.util.*;
import java.util.logging.Logger;

public class MysqlSqlParse extends AbstractSqlParse {

    private static final Logger log = Logger.getLogger(String.valueOf(MysqlSqlParse.class));


    public List<TableItem> parseCreateSql(String sql, String dbtype) {
        List<TableItem> list = new LinkedList<>();

        //去掉`
        sql = StringHelper.replaceAll(sql,"`","").toString();
        SQLStatementParser statementParser = SQLParserUtils.createSQLStatementParser(sql, SqlParseConstant.MYSQL);
        List<SQLStatement> stateList = statementParser.parseStatementList();
        //循环解析每个表
        for(SQLStatement sqlStatement:stateList) {
            if (sqlStatement instanceof SQLCreateTableStatement) {
                TableItem tableItem = new TableItem();
                List<Column> columnList = new LinkedList<>();
                SQLCreateTableStatement sqlCreateTableStatement = (SQLCreateTableStatement) sqlStatement;
                SQLName name = sqlCreateTableStatement.getName();
                SQLExpr tableComment = sqlCreateTableStatement.getComment();
                tableItem.setTable(String.valueOf(name));
                tableItem.setComment(String.valueOf(tableComment));
                tableItem.setComment(StringHelper.replaceAll(tableItem.getComment(), ISqlParse.SINGLE_QUOTES,"").toString());
                //注释去掉单引号
                List<ForeignItem> foreignItems= new ArrayList<>();
                List<SQLTableElement> tableElementList = sqlCreateTableStatement.getTableElementList();
                for (SQLTableElement sqlTableElement : tableElementList) {

                    if (sqlTableElement instanceof SQLColumnDefinition) {
                        Column column = new Column();
                        SQLColumnDefinition sqlColumnDefinition = (SQLColumnDefinition) sqlTableElement;
                        String columnName = ((SQLColumnDefinition) sqlTableElement).getColumnName();
                        if(!StringHelper.isEmpty(columnName)) {
                            SQLDataType dataType = sqlColumnDefinition.getDataType();
                            SQLExpr comment = sqlColumnDefinition.getComment();
                            column.setFieldName(columnName);
                            column.setDataType(String.valueOf(dataType));
                            column.setComment(String.valueOf(comment));
                            //注释去掉单引号
                            column.setComment(StringHelper.replaceAll(column.getComment(), ISqlParse.SINGLE_QUOTES,"").toString());
                            if(sqlColumnDefinition.containsNotNullConstaint()){
                                column.setAllownull(false);
                            } else {
                                column.setAllownull(true);

                            }
                            columnList.add(column);
                        }else{
                            continue;
                        }

                    } else {
                        //MySqlPrimaryKey主键
                        if (sqlTableElement instanceof SQLPrimaryKey) {
                            SQLPrimaryKey sqlPrimaryKey = (SQLPrimaryKey) sqlTableElement;
                            List<SQLSelectOrderByItem> columns = sqlPrimaryKey.getColumns();
                            List<String> pkFieldList = new ArrayList<>();
                            for (SQLSelectOrderByItem item : columns) {
//                                System.out.println("pk column name:" + item.getExpr());
                                pkFieldList.add(String.valueOf(item.getExpr()));
                            }
                            tableItem.setPkColumns(pkFieldList);
                        }
                        //MysqlForeignKey外键
                        if (sqlTableElement instanceof SQLForeignKeyConstraint) {
                            SQLForeignKeyConstraint sqlForeignKeyConstraint = (SQLForeignKeyConstraint) sqlTableElement;
                            ForeignItem foreignItem = new ForeignItem();
                            foreignItem.setName(String.valueOf(sqlForeignKeyConstraint.getName()));
                            foreignItem.setParentTableName(String.valueOf(sqlForeignKeyConstraint.getReferencedTableName()));
//                            System.out.println("parent tablename:" + sqlForeignKeyConstraint.getReferencedTableName());
                            List<String> parentFieldNames = new ArrayList<>();
                            for (SQLName columnName : sqlForeignKeyConstraint.getReferencedColumns()) {
//                                System.out.println("parent column:" + columnName);
                                parentFieldNames.add(String.valueOf(columnName));
                            }
                            foreignItem.setParentFieldNameList(parentFieldNames);
                            List<String> childFieldNames = new ArrayList<>();
                            for (SQLName columnName : sqlForeignKeyConstraint.getReferencingColumns()) {
//                                System.out.println("child column:" + columnName);
                                childFieldNames.add(String.valueOf(columnName));
                            }
                            foreignItem.setChildFieldNameList(childFieldNames);
                            foreignItems.add(foreignItem);
//                    System.out.println("fk info:"+JSON.toJSONString(sqlForeignKeyConstraint));
                        }
//                System.out.println(JSON.toJSONString(sqlTableElement));
                    }

                }
                tableItem.setDbtype(dbtype);
                 tableItem.setColumn(columnList);
                if(!foreignItems.isEmpty()){
                    tableItem.setForeignItems(foreignItems);
                }
                list.add(tableItem);
            }
        }
        return list;
        }


}





